<?php
/**
 * API接口
 */

require_once 'config/config.php';
require_once 'includes/db.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '无效的请求方法']);
    exit;
}

// 检查是否已安装
if (!file_exists(__DIR__ . '/config/installed.lock')) {
    echo json_encode(['success' => false, 'message' => '系统未安装']);
    exit;
}

// 检查管理员登录
if (!$_SESSION['admin_logged_in']) {
    echo json_encode(['success' => false, 'message' => '请先登录管理员账号']);
    exit;
}

$action = $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'generate_link':
            generateDirectLink();
            break;
        default:
            echo json_encode(['success' => false, 'message' => '无效的操作']);
    }
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

/**
 * 生成直链
 */
function generateDirectLink() {
    // 验证CSRF令牌
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        throw new Exception('安全验证失败');
    }

    // 接收参数
    $fileId = intval($_POST['id'] ?? 0);

    if ($fileId <= 0) {
        throw new Exception('参数错误');
    }

    // 查询文件信息
    $db = new Database();
    $file = $db->fetchOne("SELECT * FROM files WHERE id = ?", [$fileId]);

    if (!$file) {
        throw new Exception('文件不存在');
    }

    // 检查是否已生成直链
    if (!empty($file['direct_link'])) {
        throw new Exception('该文件已生成直链');
    }

    // 生成直链
    $link = $db->generateDirectLink($fileId);

    echo json_encode([
        'success' => true,
        'message' => '直链生成成功',
        'link' => $link
    ]);
}
